package com.bookseek.xreader.views.adapter;

import android.content.Context;
import android.os.Build;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SizeUtils;
import com.bookseek.xreader.R;
import com.bookseek.xreader.consts.XreaderConts;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.JkhlUtils;
import com.bookseek.xreader.utils.OkHttpUtils;
import com.bookseek.xreader.views.custom.DxmCustomTextView;
import com.bookseek.xreader.vo.TxtReadLineVo;

import org.w3c.dom.Text;

import java.util.List;

public class BookReaderAdapter extends RecyclerView.Adapter<BookReaderAdapter.BookViewHolder> {

    private List<TxtReadLineVo> datas;

    private View.OnClickListener itemClickFunc;

    private float fontSizeWenSp = 20;

    private float fontSizeYiSp = 14;



    private Context context;

    public BookReaderAdapter(List<TxtReadLineVo> datas,View.OnClickListener itemClickFunc,Context context) {
        this.datas = datas;
        this.itemClickFunc = itemClickFunc;
        this.context = context;
    }


    public void updateFontSize(float fontSizeWenSp,float fontSizeYiSp){
        this.fontSizeWenSp = fontSizeWenSp;
        this.fontSizeYiSp = fontSizeYiSp;
    }


    public void updateDatas(List<TxtReadLineVo> lines){
        if(datas!= null){
            datas.clear();
            if(lines != null){
                datas.addAll(lines);
            }
            notifyDataSetChanged();
        }
    }

    public TxtReadLineVo getDataItem(int pos){
        return datas != null && datas.size() > pos ? datas.get(pos) : null;
    }



    public TxtReadLineVo getFirstVisitWenInfo(int pos){
        if(datas != null && datas.size() > pos){
            for(int index = pos;index >= 0;index--){
                TxtReadLineVo lineVo = datas.get(index);
                if(lineVo.wy != null && lineVo.wy == XreaderConts.WY_TYPE_WEN){
                    return lineVo;
                }
            }
        }
        return null;
    }
    public String getDataItemJson(int pos){
        return OkHttpUtils.gson.toJson(getDataItem(pos));
    }



    @NonNull
    @Override
    public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.txt_line_item, parent, false);

        return new BookViewHolder(view);
    }

    /**
     * 兼容低版本设置TextView行高
     * @param textView 目标TextView
     * @param targetLineHeightPx 目标行高（单位：px）
     */
    public static void setLineHeight(TextView textView,float targetLineHeightPx, Context context) {
        // 2. 获取当前字体大小（px）
        float textSizePx = textView.getTextSize();

        // 3. 计算需要额外添加的行间距（行高 = 字体大小 + 行间距）
        float extraSpacing = targetLineHeightPx - textSizePx;

        // 4. 设置行间距（第二个参数为倍数，通常设为1）
        textView.setLineSpacing(extraSpacing, 1f);
    }

    private void setTextLineHeight(TextView textView,float fontSizeSp){
       int lineHeightPx = SizeUtils.sp2px(fontSizeSp * 2f);
        DLog.info(fontSizeSp,"sp","设置行高----------》",lineHeightPx," px");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            textView.setLineHeight(lineHeightPx);
        }else{
            setLineHeight(textView,lineHeightPx,context);
        }
    }
    @Override
    public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {

        TxtReadLineVo lineVo = datas.get(position);
        String line = lineVo.txt;
        if(JkhlUtils.isBlank(line)){
            return;
        }
        int strLen = line.length();
        int color = lineVo.color;
        //标题颜色
        if(lineVo.wy != null ){
            //文
            if(lineVo.wy == XreaderConts.WY_TYPE_WEN){
                if(color == 0){
                    color = XreaderConts.WY_TYPE_WEN_DEFAULT_COLOR;
                }
                holder.txtLineTv.setTextColor(color);
                holder.txtLineTv.setTextSize(fontSizeWenSp);
                //setTextLineHeight(holder.txtLineTv,fontSizeWenSp);
                //holder.txtLineTv.setText(line);
                SpannableString spanText = new SpannableString(lineVo.txt);
                if(lineVo.colorStart != null && lineVo.colorStart >= 0 && lineVo.colorEnd != null && lineVo.colorEnd <= lineVo.end){
                    int offset = lineVo.start - 0;
                    ForegroundColorSpan hightColor = new ForegroundColorSpan(ContextCompat.getColor(context,R.color.layui_light_green_color));
                    spanText.setSpan(hightColor,lineVo.colorStart-offset,lineVo.colorEnd-offset, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                }
                holder.txtLineTv.setText(spanText);

            }else{
                //译
                if(color == 0){
                    color = XreaderConts.WY_TYPE_YI_DEFAULT_COLOR;
                }
                holder.txtLineTv.setTextColor(color);
                holder.txtLineTv.setTextSize(fontSizeYiSp);
                //setTextLineHeight(holder.txtLineTv,fontSizeYiSp);
                holder.txtLineTv.setText(line);

            }

        }
        holder.currentPosition = position;
    }

    public void updateFontColor(int wenColor,int yiColor){
        for(TxtReadLineVo lineVo :datas){
            if(lineVo.wy == XreaderConts.WY_TYPE_WEN && wenColor != 0){
                lineVo.color = wenColor;
            }else if(yiColor != 0){
                lineVo.color = yiColor;
            }
        }
        if(wenColor != 0 || yiColor != 0){
            notifyDataSetChanged();
        }
    }

    @Override
    public int getItemCount() {
        return datas != null ? datas.size() : 0;
    }

    class BookViewHolder extends  RecyclerView.ViewHolder{

        TextView txtLineTv;
        int currentPosition;
        public BookViewHolder(@NonNull View itemView) {
            super(itemView);
            itemView.setOnClickListener(itemClickFunc);
            txtLineTv = itemView.findViewById(R.id.txtLineTv);
            txtLineTv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
                    @Override
                    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                        // 加载自定义菜单（如“复制”“翻译”）
                        menu.clear();
                        mode.getMenuInflater().inflate(R.menu.menu_custom_selection, menu);
                        DLog.info(" menu.size()=>", menu.size());
                        return true;
                    }

                    @Override
                    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                        return false; // 无需动态更新菜单
                    }

                    @Override
                    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                        // 获取当前选中的文本
                        CharSequence selectedText = getSelectedText();
                        DLog.info("=========>selectedText=",selectedText,item.getItemId());
                        if (selectedText == null) {
                            mode.finish();
                            return true;
                        }
                        if(item.getItemId() == R.id.action_copy){
                            // 复制选中的文本（示例）
                            copyToClipboard(selectedText.toString());
                            Toast.makeText(txtLineTv.getContext(),
                                    "已复制：" + selectedText, Toast.LENGTH_SHORT).show();
                            mode.finish();
                            return true;
                        }
                        if(item.getItemId() ==R.id.action_translate ){
                            // 翻译选中的文本（可结合当前 Item 位置获取更多数据）
                            String itemContent =getDataItem(currentPosition).txt;
                            Toast.makeText(txtLineTv.getContext(),
                                    "翻译《" + itemContent + "》中的：" + selectedText,
                                    Toast.LENGTH_SHORT).show();
                            mode.finish();
                            return true;
                        }
                        if(item.getItemId() == R.id.action_search){
                            Toast.makeText(txtLineTv.getContext(),
                                    "搜索" + selectedText,
                                    Toast.LENGTH_SHORT).show();
                            mode.finish();
                        }
                        return false;
                    }
                    @Override
                    public void onDestroyActionMode(ActionMode mode) {
                        // 选单关闭时无需额外操作
                    }
                    // 获取当前 TextView 中选中的文本
                    private CharSequence getSelectedText() {
                        int start = txtLineTv.getSelectionStart();
                        int end = txtLineTv.getSelectionEnd();
                        if (start >= 0 && end > start) {
                            return txtLineTv.getText().subSequence(start, end);
                        }
                        return null;
                    }
                    // 复制文本到剪贴板
                    private void copyToClipboard(String text) {
                        android.content.ClipboardManager clipboard =
                                (android.content.ClipboardManager) txtLineTv.getContext()
                                        .getSystemService(android.content.Context.CLIPBOARD_SERVICE);
                        android.content.ClipData clip = android.content.ClipData
                                .newPlainText("选中文本", text);
                        clipboard.setPrimaryClip(clip);
                    }
                });

        }
    }
}
